package com.lanyou.cook.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.ui.velocity.VelocityEngineFactoryBean;

import com.google.gson.JsonObject;
import com.lanyou.cook.common.Constants;
import com.lanyou.cook.entity.domain.ParamSetting;
import com.lanyou.cook.entity.domain.userManagement.MailSenderInfo;
import com.lanyou.cook.paramsetting.Keys;
import com.lanyou.cook.paramsetting.ParamSettingReppository;
import com.lanyou.cook.paramsetting.ParamSettingService;
import com.lanyou.cook.service.ApplicationContextKeeper;
import com.lanyou.cook.util.gson.GsonUtil;


public class MailUtil {

	static Logger log = Logger.getLogger(MailUtil.class);
	
	
	public static boolean sendMail(MailSenderInfo mailSenderInfo){
		JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
		senderImpl.setHost(mailSenderInfo.getMailServerHost());
		SimpleMailMessage msg = createMimeMessage(mailSenderInfo);
		
		senderImpl.setUsername(mailSenderInfo.getUserName()); // 根据自己的情况,设置username
		senderImpl.setPassword(mailSenderInfo.getPassword()); // 根据自己的情况, 设置password
		
		
		Properties prop = new Properties();
		prop.put(" mail.smtp.auth ", " true "); // 将这个参数设为true，让服务器进行认证,认证用户名和密码是否正确
		prop.put(" mail.smtp.timeout ", " 25000 ");
		senderImpl.setJavaMailProperties(prop);
		try{
			senderImpl.send(msg);
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
		
		return true;
	}
	
	

	/* 
	 * 根据 mailSenderInfo 创建 MimeMessage
	 */
	private static SimpleMailMessage createMimeMessage(MailSenderInfo mailSenderInfo){
		if (!checkMailBean(mailSenderInfo)) {
			return null;
		}
		SimpleMailMessage mailMessage = new SimpleMailMessage();
		mailMessage.setTo(mailSenderInfo.getToAddress());
		mailMessage.setFrom(mailSenderInfo.getFromAddress());
		try {
			System.out.println("-----------------------------------------------------------" + mailSenderInfo.getSubject());
			mailMessage.setSubject(new String(mailSenderInfo.getSubject().getBytes("utf-8")));
			mailMessage.setText(new String(mailSenderInfo.getContent().getBytes("utf-8")));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return mailMessage;
	}
	
	
	
	/*
	 * check 邮件
	 */
	private static boolean checkMailBean(MailSenderInfo mailSenderInfo) {
		if (mailSenderInfo == null) {
			log.warn("@@@ warn mailBean is null (Thread name=" + Thread.currentThread().getName() + ") ");
			return false;
		}
		if (mailSenderInfo.getSubject() == null) {
			log.warn("@@@ warn mailBean.getSubject() is null (Thread name=" + Thread.currentThread().getName() + ") ");
			return false;
		}
		if (mailSenderInfo.getToAddress() == null) {
			log.warn("@@@ warn mailBean.getToEmails() is null (Thread name=" + Thread.currentThread().getName() + ") ");
			return false;
		}
		return true;
	}
	
	public static Map EmailEngine(){
		JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl();
		ParamSettingService paramSettingService = ApplicationContextKeeper.getApplicationContext().getBean(ParamSettingService.class);
		JsonObject smtpService = paramSettingService.getAsJson(Keys.SMTP).getAsJsonObject();
		javaMailSenderImpl.setHost(GsonUtil.getString(smtpService, "smtpAddress", ""));
		javaMailSenderImpl.setPort(Integer.parseInt(GsonUtil.getString(smtpService, "port", "")));
		javaMailSenderImpl.setUsername(GsonUtil.getString(smtpService, "userCode", ""));
		javaMailSenderImpl.setPassword(GsonUtil.getString(smtpService, "password", ""));
		
		
		Properties javaMailProperties = new Properties();
		javaMailProperties.put(" mail.smtp.auth ", " true "); // 将这个参数设为true，让服务器进行认证,认证用户名和密码是否正确
		javaMailProperties.put(" mail.smtp.timeout ", " 25000 ");
		javaMailSenderImpl.setJavaMailProperties(javaMailProperties);
		
		VelocityEngineFactoryBean velocityEngineFactoryBean = new VelocityEngineFactoryBean();
		velocityEngineFactoryBean.setResourceLoaderPath("templates");
		Map map = new HashMap();
		try {
			map.put("velocityEngine", velocityEngineFactoryBean.createVelocityEngine());
			map.put("smtpService", smtpService);
			map.put("javaMailSenderImpl", javaMailSenderImpl);
		} catch (VelocityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return map;
	}
	/*public static void main(String[] args) {
		MailSenderInfo mailSenderInfo = new MailSenderInfo();
		mailSenderInfo.setToAddress("yangchr@szlanyou.com");
		mailSenderInfo.setSubject(" 测试简单文本邮件发送！ ");
		mailSenderInfo.setContent(" 测试我的简单邮件发送机制！！ ");
		MailUtil.sendMail(mailSenderInfo);
		System.out.println(" 邮件发送成功.. ");
	}*/
}
